<template>
  <div class="common-layout">
    <el-container>
      <el-header style="padding:0;">
        <el-row style="height: 100%;">
          <el-col :span="16" style=" display: flex; align-items: center;">
            <el-input v-model="input" style="width: 240px;height: 36px; margin-right: 10px;" placeholder="搜索名称"
              clearable />
            <el-divider direction="vertical" />
            <el-button type="success" style="margin-left: 10px;" size="small" @click="addItemFn">新增</el-button>
          </el-col>

          <el-col :span="8">

          </el-col>

        </el-row>
      </el-header>
      <el-main style="padding: 10px 0;">
        <el-table ref="tableRef" :data="filteredData" style="width: 100%; " row-key="id" border table-layout="auto"
          :indent="10" @row-dblclick="rowDblClickFn">
          <!-- <el-table-column prop="id" label="ID" width="50" align="center">
        
      </el-table-column> -->
          <el-table-column prop="id" label="ID" fixed="left" v-if="!isMobile" />
          <!-- <el-table-column prop="name" label="父ID" sortable /> -->
          <el-table-column prop="name" label="名称" width="200" />
          <!-- <el-table-column prop="address" label="显示顺序" min-width="120" /> -->
          <!-- <el-table-column prop="address" label="类型" sortable /> -->
          <el-table-column prop="type" label="文件类型" min-width="50">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-icon v-if="scope.row.type === 1" size="20" color="blue">
                  <Document />
                </el-icon>
                <el-icon v-else size="20" color="orange">
                  <FolderOpened />
                </el-icon>
                <span style="margin-left: 10px">{{ scope.row.type === 0 ? '目录' : '文件' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="qrCode" label="二维码">
            <template #default="scope">
              <div style="display: flex; align-items: center; justify-content: center;">
                <!-- <img :src="scope.row.qrCode" alt="二维码" style="width: 50px;" @click="clickSaleFn(scope.row.qrCode)" /> -->

                <el-popover :width="350"
                  popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 0px;">
                  <template #reference>
                    <el-avatar :src="scope.row.qrCode" shape="square" />
                  </template>
                  <template #default>
                    <div class="demo-rich-conent" style="display: flex; justify-content: center;">
                      <el-avatar :size="350" :src="scope.row.qrCode" shape="square" />
                    </div>
                  </template>
                </el-popover>

              </div>
            </template>
          </el-table-column>

          <el-table-column prop="fileUrl" label="文件地址" show-overflow-tooltip min-width="300" v-if="!isMobile">
            <template #default="scope">
              <el-link :href="scope.row.previewUrl" target="_blank">{{ scope.row.fileUrl }}</el-link>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="status" label="状态" sortable width="100">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span style="margin-left: 0px">{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
              </div>
            </template>
          </el-table-column> -->

          <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.type === 0" type="success" size="small" @click="addItemFn(scope.row)">
                新增
              </el-button>
              <el-button type="primary" size="small" @click="updateItemFn(scope.row)">
                修改
              </el-button>
              <el-button type="danger" size="small" @click="deleteItemFn(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>


        </el-table>
      </el-main>
    </el-container>

    <!-- <el-table :data="tableData1" style="width: 100%" row-key="id" border lazy :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="date" label="Date" />
      <el-table-column prop="name" label="Name" />
      <el-table-column prop="address" label="Address" />
    </el-table> -->
  </div>

  <el-dialog v-model="dialogFormVisible" :title="`${isEdit ? '修改' : '新增'}目录/文件`" width="500" @closed="dialogClosedFn"
    :close-on-click-modal="false">
    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-position="left" px="10">
      <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off" clearable placeholder="请输入文件/目录名称" />
      </el-form-item>

      <el-space fill>
        <el-alert type="info" show-icon :closable="false">
          <el-popover placement="right" title="支持格式" :width="500" trigger="click" content="
          支持 doc, docx, xls, xlsx, xlsm, ppt, pptx, csv, tsv, dotm, xlt, xltm, dot, dotx, xlam, xla, pages 等 Office 办公文档
          支持 odt, ods, ots, odp, otp, six, ott, fodt, fods 等OpenOffice、LibreOffice 办公文档
          支持 vsd, vsdx 等 Visio 流程图文件
          支持 wmf, emf 等 Windows 系统图像文件
          支持 psd, eps 等 Photoshop 软件模型文件
          支持 pdf ,ofd, rtf 等文档
          支持 xmind 软件模型文件
          支持 bpmn 工作流文件
          支持 eml 邮件文件
          支持 epub 图书文档
          支持 obj, 3ds, stl, ply, gltf, glb, off, 3dm, fbx, dae, wrl, 3mf, ifc, brep, step, iges, fcstd, bim 等 3D 模型文件
          支持 dwg, dxf, dwf, iges , igs, dwt, dng, ifc, dwfx, stl, cf2, plt 等 CAD 模型文件
          支持 txt, xml(渲染), md(渲染), java, php, py, js, css 等所有纯文本
          支持 zip, rar, jar, tar, gzip, 7z 等压缩包
          支持 jpg, jpeg, png, gif, bmp, ico, jfif, webp 等图片预览（翻转，缩放，镜像）
          支持 tif, tiff 图信息模型文件
          支持 tga 图像格式文件
          支持 svg 矢量图像格式文件
          支持 mp3,wav,mp4,flv 等音视频格式文件
          支持 avi,mov,rm,webm,ts,rm,mkv,mpeg,ogg,mpg,rmvb,wmv,3gp,ts,swf 等视频格式转码预览
          支持 dcm 等医疗数位影像预览
          支持 drawio 绘图预览">
            <template #reference>
              <!-- <el-button class="m-2">Click to activate</el-button> -->
              <p>支持 doc, docx, xls, ppt, pptx等...点击查看更多</p>
            </template>
          </el-popover>

        </el-alert>
        <el-form-item label="文件类型" :label-width="formLabelWidth" prop="type">
          <el-select v-model="form.type" placeholder="选择文件类型" :disabled="isEdit">
            <el-option label="目录" :value="0" />
            <el-option label="文件" :value="1" />
          </el-select>
        </el-form-item>
      </el-space>

      <el-form-item label="文件地址" :label-width="formLabelWidth" v-show="form.type === 1" prop="fileUrl">
        <!-- <el-upload v-model:file-list="fileList" class="upload-demo"
          action="http://183.230.28.133:2023/qr-api/minio/upload" :on-change="handleChange" :limit="1"
          :on-exceed="handleExceed" :on-error="handleError">
          <el-button type="primary">点击上传</el-button>
        </el-upload> -->
        <el-upload v-model:file-list="fileList" class="upload-demo" :action="uploadUrl" :on-change="handleChange"
          :limit="1" :on-exceed="handleExceed" :on-error="handleError">
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="default">取消</el-button>
        <el-button type="primary" @click="submitFn(ruleFormRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script lang="ts" setup name="QRcodeAdmin">
import { Document, FolderOpened } from '@element-plus/icons-vue'
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'

import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { uploadUrl, addFile, deleteItem, editItem, getListTreeById } from '~/Api/request'
import { isEmpty } from 'element-plus/es/utils/index'
import { computed } from 'vue'


const isMobile = ref(window.innerWidth < 768);

const updateWindowSize = () => {
  isMobile.value = window.innerWidth < 768;

  // if (isMobile.value) {
  //   console.log('移动端');
  // } else {
  //   console.log('非移动端');
  // }
};
// 使用watch来监听窗口大小变化（也可以使用其他方式）
watch(() => window.innerWidth, (newVal, oldVal) => {
  updateWindowSize();
},
  { immediate: false }
);
onMounted(() => {
  window.addEventListener("resize", updateWindowSize);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", updateWindowSize);
});

interface fileInter {
  id?: string
  name: string
  type: number
  fileUrl: string
  qrCode?: string
  status?: string
  children?: any[]
  Expand?: boolean
}

let qrCodeList = ref<fileInter[]>([])

//搜索框
let input = ref<string>('')

//表格
const tableRef = ref();

//是否在编辑
let isEdit = ref(false)

//dialog对框
const form = reactive<fileInter>({
  name: '',
  type: 0,
  fileUrl: '',
})

const dialogFormVisible = ref(false)
const formLabelWidth = '100px'

// const load = (
//   row: User,
//   treeNode: unknown,
//   resolve: (date: User[]) => void
// ) => {
//   setTimeout(() => {
//     resolve([
//       {
//         id: 31,
//         date: '2016-05-01',
//         name: 'wangxiaohu',
//         address: 'No. 189, Grove St, Los Angeles',
//       },
//       {
//         id: 32,
//         date: '2016-05-01',
//         name: 'wangxiaohu',
//         address: 'No. 189, Grove St, Los Angeles',
//       },
//     ])
//   }, 1000)
// }

// const tableData: User[] = [
//   {
//     id: 1,
//     date: '2016-05-02',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     id: 2,
//     date: '2016-05-04',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     id: 3,
//     date: '2016-05-01',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//     children: [
//       {
//         id: 31,
//         date: '2016-05-01',
//         name: 'wangxiaohu',
//         address: 'No. 189, Grove St, Los Angeles',
//       },
//       {
//         id: 32,
//         date: '2016-05-01',
//         name: 'wangxiaohu',
//         address: 'No. 189, Grove St, Los Angeles',
//       },
//     ],
//   },
//   {
//     id: 4,
//     date: '2016-05-03',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
// ]

// const tableData1: User[] = [
//   {
//     id: 1,
//     date: '2016-05-02',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     id: 2,
//     date: '2016-05-04',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     id: 3,
//     date: '2016-05-01',
//     name: 'wangxiaohu',
//     hasChildren: true,
//     address: 'No. 189, Grove St, Los Angeles',
//   },
//   {
//     id: 4,
//     date: '2016-05-03',
//     name: 'wangxiaohu',
//     address: 'No. 189, Grove St, Los Angeles',
//   },
// ]

onMounted(() => {
  getListFn()
})

let pageInde = 1
let pageSize = 15
let searchKey = ''

function getListFn() {

  // getFileList(pageInde, pageSize, searchKey).then(res => {
  //   let { records } = res.data.data
  //   qrCodeList.value = records
  //   console.log(records, qrCodeList);
  // })

  getListTreeById(undefined).then(res => {
    qrCodeList.value = res.data.data
    console.log(qrCodeList);
  })

}

//筛选按name
// const filterNameData = computed(() => {
//   if (input.value.trim() === '') {
//     // 如果搜索文本为空，则返回原始数据
//     return [...qrCodeList.value];
//   }

//   return [...qrCodeList.value].filter(item =>
//     item.name.toLowerCase().includes(input.value.toLowerCase())
//   );

// });

// 递归函数，用于筛选数据
function filterData(data: fileInter[], searchQuery: string): fileInter[] {
  if (!searchQuery) return data; // 如果没有搜索查询，返回原始数据

  return data.flatMap(item => {
    const matches = item.name.toLowerCase().includes(searchQuery.toLowerCase());
    const filteredChildren = item.children ? filterData(item.children, searchQuery) : [];

    // 如果当前项匹配或者其子项匹配，则包含当前项
    if (matches || filteredChildren.length > 0) {
      return [{
        ...item,
        children: filteredChildren, // 只有当有匹配的子项时才包含子项
      }];
    }
    return []; // 如果当前项及其子项都不匹配，则不包含当前项
  });
}

// 计算属性，用于根据输入值过滤数据
const filteredData = computed(() => {
  const searchQuery = input.value.trim();
  return filterData(qrCodeList.value, searchQuery);
});


//上传
const fileList = ref<UploadUserFile[]>([

])

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('只能添加一个文件')
}

const handleError: UploadProps['onError'] = (err, file, fileList) => {
  console.log('文件上传失败', err, fileList);
  ElMessage.error('上传失败')
}

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  // console.log('文件发生改变', uploadFiles);

  try {
    fileList.value = fileList.value.slice(-3)

    // console.log('文件添加后', fileList.value);

    let [file] = fileList.value

    console.log('文件添加后', fileList);
    // form.fileUrl = file.response?.data
    if (file) {
      form.fileUrl = (file.response as { data: any }).data;
    } else {
      form.fileUrl = ''
    }
  } catch (error) {
    console.log(error);
  }

}

//提交验证
const ruleFormRef = ref<FormInstance>()
//自定义判断文件地址
const validatePass = (rule: any, value: any, callback: any) => {
  if (form.type === 1) {
    if (value === '') {
      callback(new Error('请上传文件'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}


const rules = reactive<FormRules<fileInter>>({

  name: [
    { required: true, message: '请输入文件名称', trigger: 'blur' },
    { min: 1, max: 20, message: '名称长度大于1或者小于20个字符以内', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  fileUrl: [
    // { required: true, message: '请上传文件', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],

})

//关闭对话框

const dialogClosedFn = () => {
  isEdit.value = false

  //还原数据
  parentId = '0'
  form.id = undefined
  form.name = ''
  form.type = 0
  form.fileUrl = ''

  fileList.value = []
}

// 声明一个parentId 默认为0
let parentId: string = '0'

//增加
function addItemFn(row: fileInter | any) {
  dialogFormVisible.value = true

  //如果有值，则是为目录添加子级
  if (!isEmpty(row.id)) {
    // ElMessage.success(row.id)
    parentId = row.id
  }

}

//删除
function deleteItemFn(row: fileInter) {

  const fileType = (row.type === 0 ? '目录' : '文件')

  // ElMessageBox.confirm(
  //   `是否删除${fileType} '${row.name}'的数据`,
  //   '提示',
  //   {
  //     confirmButtonText: '删除',
  //     cancelButtonText: '取消',
  //     type: 'info',
  //   }
  // )
  //   .then(() => {
  //     deleteItem([row.id] as string[]).then((res) => {
  //       const { msg } = res.data
  //       ElMessage.success(msg)
  //       getListFn()
  //     }).catch((err) => {
  //       ElMessage.error(err)
  //     })
  //   })

  ElMessageBox.prompt('请输入公司座机号:02385289111,用以确认删除文件!', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    inputPattern: /^02385289111$/,
    inputErrorMessage: '请输入正确的公司座机号！',
  })
    .then(({ value }) => {
      // ElMessage({
      //   type: 'success',
      //   message: `Your email is:${value}`,
      // })
      deleteItem([row.id] as string[]).then((res) => {
        const { msg } = res.data
        ElMessage.success(msg)
        getListFn()
      }).catch((err) => {
        ElMessage.error(err)
      })
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: 'Input canceled',
      // })
    })
}

//修改
function updateItemFn(row: fileInter) {
  isEdit.value = true

  form.id = row.id
  form.name = row.name
  form.type = row.type
  form.fileUrl = row.fileUrl
  fileList.value = []

  dialogFormVisible.value = true
}

const submitFn = async (formEl: FormInstance | undefined) => {

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    //通过验证
    if (valid) {
      // console.log('submit!')

      //判断是否是在修改数据
      if (isEdit.value) {
        // console.log(form)
        //修改
        editItem(form.id as string, form.name, form.type, form.fileUrl).then((res) => {
          const { msg } = res.data
          ElMessage.success(msg)
          form.name = ''
          form.fileUrl = ''
          fileList.value = []
          getListFn()
        }).catch((err) => {
          ElMessage.error(err)
        }).finally(() => {
          dialogFormVisible.value = false
        })
      } else {
        //关闭
        dialogFormVisible.value = false
        //文件类型
        if (form.type === 1) {
          addFile(form.name, Number(form.type), form.fileUrl, parentId).then((res) => {
            // console.log(res);
            const { msg } = res.data
            ElMessage.success(msg)
            form.name = ''
            form.fileUrl = ''
            fileList.value = []
            getListFn()
          }).catch((err) => {
            fileList.value = []
            ElMessage.error(err)
          })
        } else {
          //添加目录
          addFile(form.name, Number(form.type), undefined, parentId).then((res) => {
            const { msg } = res.data
            ElMessage.success(msg)
            form.name = ''
            getListFn()
          }).catch((err) => {
            ElMessage.error(err)
          })
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}


const rowDblClickFn = (row: any, column: any, event: Event) => {
  // console.log(1111, row.Expand);
  // console.log(2222, column);
  // console.log(tableRef.value);

  if (row.type === 0 && row.children.length > 0) {
    row.Expand = !row.Expand
    tableRef.value!.toggleRowExpansion(row, row.Expand)
  } else if (row.type === 1) {
    // 假设 row.url 是跳转的目标网页地址
    const url = row.previewUrl; // 替换为实际的 URL 属性
    const target = '_blank'; // 表示在新窗口打开
    const options = 'noopener,noreferrer'; // 增加安全性

    window.open(url, target, options);
  }
}

</script>

<style scoped>
.upload-demo {
  width: 100%;
}

:deep(.ep-upload-list__item .ep-progress__text) {
  right: -25px;
  color: #67c23a;
}
</style>